/*
 * Created by JFormDesigner on Sun Mar 27 12:12:59 CST 2022
 */

package com.wangcanxuan.www.view.tribe;

import com.wangcanxuan.www.controller.ApplyController;
import com.wangcanxuan.www.controller.Impl.ApplyControllerImpl;
import com.wangcanxuan.www.controller.Impl.TribeControllerImpl;
import com.wangcanxuan.www.controller.Impl.UserControllerImpl;
import com.wangcanxuan.www.controller.TribeController;
import com.wangcanxuan.www.controller.UserController;
import com.wangcanxuan.www.entity.dto.ResultInfo;
import com.wangcanxuan.www.entity.po.Role;
import com.wangcanxuan.www.entity.po.Tribe;
import com.wangcanxuan.www.entity.po.User;
import com.wangcanxuan.www.proxy.ControllerProxy;
import com.wangcanxuan.www.util.ValidateUtil;
import com.wangcanxuan.www.view.user.MainView;

import java.awt.*;
import java.awt.event.*;
import java.util.List;
import java.util.Vector;
import javax.swing.*;
import javax.swing.table.*;

import static com.wangcanxuan.www.entity.dto.ResultConstants.*;

/**
 * 部落大厅界面
 *
 * @author unknown
 * @date 2022/04/01
 */
public class TribalHallView extends JFrame {
    private final User user;
    private Tribe tribe;
    private int page;
    private String searchName;
    private final TribeController tribeController;
    private final UserController userController;
    private final ApplyController applyController;
    private String chooseTribeName;

    public TribalHallView(User user) {
        page = 1;
        this.user = user;
        userController = ControllerProxy.getProxyInstance(UserControllerImpl.class);
        tribeController = ControllerProxy.getProxyInstance(TribeControllerImpl.class);
        applyController = ControllerProxy.getProxyInstance(ApplyControllerImpl.class);
        initComponents();
        initMessage();
        setVisible(true);
    }

    private void initMessage() {
        fillTable(0);
        pageNumberText.setText(String.valueOf(1));
        nickNameText.setText(user.getNickName());
        coinsText.setText(String.valueOf(user.getCoins()));
        if (user.getCamp() == 0) {
            campText.setText("光明阵营");
        } else {
            campText.setText("黑暗阵营");
        }

        ResultInfo<Tribe> tribeResultMessage = tribeController.selectTribeByTribeId(user.getTribeId());
        if (tribeResultMessage.getObj() == null) {
            nowTribeNameText.setText("");
        } else {
            tribe = tribeResultMessage.getObj();
            nowTribeNameText.setText(tribe.getTribeName());
        }
        setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
    }

    private boolean fillTable(int pageCount) {
        ResultInfo<List<Tribe>> listResultMessage;
        if (!ValidateUtil.strIsNullOrEmpty(searchName)) {
            listResultMessage = tribeController.selectSearchTribeList(user.getCamp(), searchName, pageCount);
        } else {
            listResultMessage = tribeController.selectAllCampTribeList(user.getCamp(), pageCount);
        }
        List<Tribe> tribes = listResultMessage.getObj();
        int code = listResultMessage.getCode();
        String message = listResultMessage.getMessage();
        if (code == SUCCESS_REQUEST_CODE.getCode()) {
            DefaultTableModel dtm = (DefaultTableModel) tribeShowTable.getModel();
            // 设置成0行
            dtm.setRowCount(0);
            if (tribes.size() == 0) {
                return false;
            }
            for (Tribe tribe : tribes) {
                Vector<Object> list = new Vector<>();
                ResultInfo<Long> integerResultMessage = tribeController.selectNumbersForTribe(tribe.getId());
                list.add(tribe.getTribeName());
                list.add(tribe.getCreator());
                list.add(tribe.getCurrentLeader());
                list.add(integerResultMessage.getObj());
                list.add(tribe.getCombatPower());
                list.add(tribe.getTribeLevel());
                dtm.addRow(list);
            }
            return true;
        }
        if (code == REJECT_REQUEST_CODE.getCode()) {
            JOptionPane.showMessageDialog(null, message);
            return false;
        }
        return false;
    }


    /**
     * 返回主页
     *
     * @param e e
     */
    private void back(ActionEvent e) {
        // TODO add your code here
        ResultInfo<User> refresh = userController.refresh(user.getId());
        new MainView(refresh.getObj());
        dispose();
    }

    /**
     * 创建部落
     *
     * @param e e
     */
    private void createTribe(ActionEvent e) {
        // TODO add your code here
        new CreateTribeView(user);
        dispose();
    }

    /**
     * 申请加入
     *
     * @param e e
     */
    private void applyJoin(ActionEvent e) {
        // TODO add your code here
        if (ValidateUtil.strIsNullOrEmpty(chooseTribeName)) {
            JOptionPane.showMessageDialog(null, "请选择你要加入的部落！");
            return;
        }
        ResultInfo<?> resultMessage = applyController.applyTribe(user, chooseTribeName);
        int code = resultMessage.getCode();
        String message = resultMessage.getMessage();
        if (code == SUCCESS_REQUEST_CODE.getCode()) {
            JOptionPane.showMessageDialog(null, message);
        }
        if (code == REJECT_REQUEST_CODE.getCode()) {
            JOptionPane.showMessageDialog(null, message);
        }
    }

    /**
     * 上一页
     *
     * @param e e
     */
    private void upPage(ActionEvent e) {
        // TODO add your code here
        if (page == 1) {
            JOptionPane.showMessageDialog(null, "这是首页！");
            return;
        }
        int count = (page - 2) * 10;
        boolean b = fillTable(count);
        if (b) {
            page--;
            pageNumberText.setText(String.valueOf(page));
        }
    }

    /**
     * 下一页
     *
     * @param e e
     */
    private void downPage(ActionEvent e) {
        // TODO add your code here
        int count = page * 10;
        boolean b = fillTable(count);
        if (b) {
            page++;
            pageNumberText.setText(String.valueOf(page));
        }
    }

    /**
     * 搜索
     *
     * @param e e
     */
    private void search(ActionEvent e) {
        // TODO add your code here
        if (ValidateUtil.strIsNullOrEmpty(searchText.getText())) {
            searchName = "";
        } else {
            searchName = "%" + searchText.getText() + "%";
        }
        page = 1;
        fillTable(0);
    }

    /**
     * 部落显示鼠标按下表
     *
     * @param e e
     */
    private void tribeShowTableMousePressed(MouseEvent e) {
        // TODO add your code here
        int selectedRow = tribeShowTable.getSelectedRow();
        chooseTribeName = String.valueOf(tribeShowTable.getValueAt(selectedRow, 0));
        chooseTribeText.setText(chooseTribeName);
    }

    private void goToTribe(ActionEvent e) {
        // TODO add your code here
        ResultInfo<Role> userRole = userController.getUserRole(user.getId());
        Integer roleId = userRole.getObj().getId();
        user.setRoleId(roleId);
        if (roleId == 1) {
            JOptionPane.showMessageDialog(null, "您还未加入部落！");
            new TribalHallView(user);
            dispose();
            return;
        }
        new TribalInterfaceView(user, tribe);
        dispose();
    }

    private void initComponents() {
        // JFormDesigner - Component initialization - DO NOT MODIFY  //GEN-BEGIN:initComponents
        // Generated using JFormDesigner Evaluation license - unknown
        label1 = new JLabel();
        nickNameText = new JTextField();
        label2 = new JLabel();
        label3 = new JLabel();
        coinsText = new JTextField();
        createTribeButton = new JButton();
        label4 = new JLabel();
        campText = new JTextField();
        scrollPane1 = new JScrollPane();
        tribeShowTable = new JTable();
        upPageButton = new JButton();
        pageNumberText = new JTextField();
        downPageButton = new JButton();
        chooseTribeText = new JTextField();
        label5 = new JLabel();
        applyJoinButton = new JButton();
        backButton = new JButton();
        searchText = new JTextField();
        label6 = new JLabel();
        searchButton = new JButton();
        goToTribeButton = new JButton();
        label7 = new JLabel();
        nowTribeNameText = new JTextField();

        //======== this ========
        setTitle("\u90e8\u843d\u5927\u5385");
        Container contentPane = getContentPane();
        contentPane.setLayout(null);

        //---- label1 ----
        label1.setText("\u90e8\u843d\u5927\u5385");
        label1.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 22));
        label1.setForeground(Color.black);
        contentPane.add(label1);
        label1.setBounds(505, 18, label1.getPreferredSize().width, 36);

        //---- nickNameText ----
        nickNameText.setEditable(false);
        contentPane.add(nickNameText);
        nickNameText.setBounds(80, 115, 120, nickNameText.getPreferredSize().height);

        //---- label2 ----
        label2.setText("\u6635 \u79f0\uff1a");
        label2.setForeground(Color.black);
        contentPane.add(label2);
        label2.setBounds(30, 110, 50, 41);

        //---- label3 ----
        label3.setText("\u91d1 \u5e01\uff1a");
        label3.setForeground(Color.black);
        contentPane.add(label3);
        label3.setBounds(35, 160, 50, 29);

        //---- coinsText ----
        coinsText.setEditable(false);
        contentPane.add(coinsText);
        coinsText.setBounds(80, 160, 120, coinsText.getPreferredSize().height);

        //---- createTribeButton ----
        createTribeButton.setText("\u521b\u5efa\u90e8\u843d");
        createTribeButton.addActionListener(e -> createTribe(e));
        contentPane.add(createTribeButton);
        createTribeButton.setBounds(45, 249, 155, 47);

        //---- label4 ----
        label4.setText("\u9635 \u8425\uff1a");
        label4.setForeground(Color.black);
        contentPane.add(label4);
        label4.setBounds(35, 205, 50, 26);

        //---- campText ----
        campText.setEditable(false);
        contentPane.add(campText);
        campText.setBounds(80, 200, 120, campText.getPreferredSize().height);

        //======== scrollPane1 ========
        {

            //---- tribeShowTable ----
            tribeShowTable.setModel(new DefaultTableModel(
                    new Object[][]{
                            {null, null, null, null, null, null},
                            {null, null, null, null, null, null},
                            {null, null, null, null, null, null},
                            {null, null, null, null, null, null},
                            {null, null, null, null, null, null},
                            {null, null, null, null, null, null},
                            {null, null, null, null, null, null},
                            {null, null, null, null, null, null},
                            {null, null, null, null, null, null},
                            {null, null, null, null, null, null},
                    },
                    new String[]{
                            "\u90e8\u843d\u540d", "\u521b\u5efa\u8005", "\u5f53\u524d\u9996\u9886", "\u5f53\u524d\u4eba\u6570", "\u6218\u529b", "\u90e8\u843d\u7b49\u7ea7"
                    }
            ) {
                boolean[] columnEditable = new boolean[]{
                        false, false, false, false, false, false
                };

                @Override
                public boolean isCellEditable(int rowIndex, int columnIndex) {
                    return columnEditable[columnIndex];
                }
            });
            tribeShowTable.addMouseListener(new MouseAdapter() {
                @Override
                public void mousePressed(MouseEvent e) {
                    tribeShowTableMousePressed(e);
                }
            });
            scrollPane1.setViewportView(tribeShowTable);
        }
        contentPane.add(scrollPane1);
        scrollPane1.setBounds(215, 120, 655, 245);

        //---- upPageButton ----
        upPageButton.setText("\u4e0a\u4e00\u9875");
        upPageButton.addActionListener(e -> upPage(e));
        contentPane.add(upPageButton);
        upPageButton.setBounds(295, 395, 100, upPageButton.getPreferredSize().height);

        //---- pageNumberText ----
        pageNumberText.setEditable(false);
        contentPane.add(pageNumberText);
        pageNumberText.setBounds(460, 395, 70, pageNumberText.getPreferredSize().height);

        //---- downPageButton ----
        downPageButton.setText("\u4e0b\u4e00\u9875");
        downPageButton.addActionListener(e -> downPage(e));
        contentPane.add(downPageButton);
        downPageButton.setBounds(575, 395, 100, downPageButton.getPreferredSize().height);

        //---- chooseTribeText ----
        chooseTribeText.setEditable(false);
        contentPane.add(chooseTribeText);
        chooseTribeText.setBounds(124, 308, 86, chooseTribeText.getPreferredSize().height);

        //---- label5 ----
        label5.setText("\u9009\u62e9\u7684\u90e8\u843d\uff1a");
        label5.setForeground(Color.black);
        contentPane.add(label5);
        label5.setBounds(34, 308, label5.getPreferredSize().width, 27);

        //---- applyJoinButton ----
        applyJoinButton.setText("\u7533\u8bf7\u52a0\u5165");
        applyJoinButton.addActionListener(e -> applyJoin(e));
        contentPane.add(applyJoinButton);
        applyJoinButton.setBounds(95, 350, 110, applyJoinButton.getPreferredSize().height);

        //---- backButton ----
        backButton.setText("\u8fd4\u56de");
        backButton.addActionListener(e -> back(e));
        contentPane.add(backButton);
        backButton.setBounds(34, 30, 103, 36);
        contentPane.add(searchText);
        searchText.setBounds(595, 80, 98, searchText.getPreferredSize().height);

        //---- label6 ----
        label6.setText("\u67e5\u627e\u90e8\u843d\uff1a");
        label6.setForeground(Color.black);
        contentPane.add(label6);
        label6.setBounds(530, 80, 73, 31);

        //---- searchButton ----
        searchButton.setText("\u67e5\u627e");
        searchButton.addActionListener(e -> search(e));
        contentPane.add(searchButton);
        searchButton.setBounds(700, 80, 95, searchButton.getPreferredSize().height);

        //---- goToTribeButton ----
        goToTribeButton.setText("\u8fdb\u5165\u90e8\u843d");
        goToTribeButton.addActionListener(e -> goToTribe(e));
        contentPane.add(goToTribeButton);
        goToTribeButton.setBounds(420, 80, 110, goToTribeButton.getPreferredSize().height);

        //---- label7 ----
        label7.setText("\u5f53\u524d\u6240\u5728\u90e8\u843d\uff1a");
        label7.setFont(label7.getFont().deriveFont(label7.getFont().getStyle() & ~Font.ITALIC));
        label7.setForeground(Color.black);
        contentPane.add(label7);
        label7.setBounds(210, 80, 100, 30);

        //---- nowTribeNameText ----
        nowTribeNameText.setEditable(false);
        contentPane.add(nowTribeNameText);
        nowTribeNameText.setBounds(310, 85, 105, nowTribeNameText.getPreferredSize().height);

        {
            // compute preferred size
            Dimension preferredSize = new Dimension();
            for (int i = 0; i < contentPane.getComponentCount(); i++) {
                Rectangle bounds = contentPane.getComponent(i).getBounds();
                preferredSize.width = Math.max(bounds.x + bounds.width, preferredSize.width);
                preferredSize.height = Math.max(bounds.y + bounds.height, preferredSize.height);
            }
            Insets insets = contentPane.getInsets();
            preferredSize.width += insets.right;
            preferredSize.height += insets.bottom;
            contentPane.setMinimumSize(preferredSize);
            contentPane.setPreferredSize(preferredSize);
        }
        pack();
        setLocationRelativeTo(getOwner());
        // JFormDesigner - End of component initialization  //GEN-END:initComponents
    }

    // JFormDesigner - Variables declaration - DO NOT MODIFY  //GEN-BEGIN:variables
    // Generated using JFormDesigner Evaluation license - unknown
    private JLabel label1;
    private JTextField nickNameText;
    private JLabel label2;
    private JLabel label3;
    private JTextField coinsText;
    private JButton createTribeButton;
    private JLabel label4;
    private JTextField campText;
    private JScrollPane scrollPane1;
    private JTable tribeShowTable;
    private JButton upPageButton;
    private JTextField pageNumberText;
    private JButton downPageButton;
    private JTextField chooseTribeText;
    private JLabel label5;
    private JButton applyJoinButton;
    private JButton backButton;
    private JTextField searchText;
    private JLabel label6;
    private JButton searchButton;
    private JButton goToTribeButton;
    private JLabel label7;
    private JTextField nowTribeNameText;
    // JFormDesigner - End of variables declaration  //GEN-END:variables
}
